// pages/new-pages/resume-detail/resume-detail.js
const app = getApp();
import Toast from '../../../component/toast/toast';
let store = app.store;
import datePickerUtils from '../../../utils/datePicker';
import { formatTime } from '../../../utils/util.js'
import IMController from '../../../controller/im.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        resumeData: {},
        windowObj: {
            isShowWindow: false,
            isAnim: false
        },
        windowPosition: 1,
        authChecked: false,
        pickerDate: [],
        pickerDateIndexs: [0, 0, 0],
        startDate: '',
        endDate: '',
        workTime: '',
        orderAmount: 0,
        managerAmount: '',
        isOpenVip: false,
        checkImg: '../../../assets/icon/icon_coupon_check_select.png',
        normalImg: '../../../assets/icon/icon_coupon_check_normal.png',
        vipStatus: 0,
        monthTxt: "雇主对新合作人才有1小时免费试用，不满意退还全部订单金额与管理费。工作由闲将工作伴侣电脑软件记录，用人更放心",
        taskTxt: '任务制不支持退款，建议您分阶段以小金额下达任务',
        phoneNumber: '',
        currentTabPosition: 1,
        commentList: null,
        produceList: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.resumeId) {
            this.getFromResumeInfoById(options.resumeId);
        }
        let datePicker = datePickerUtils.getDatePicker();
        let mobileNumber = '';
        if (app.userInfo) {
            mobileNumber = app.userInfo.MobileNumber;
        }
        this.setData({
            pickerDate: datePicker,
            phoneNumber: mobileNumber
        })
        //避免分享页直接进入未登录IM
        app.userInfoReadyCallback = res => {
            this.imLogin(app.userInfo.Token, app.userInfo.Id);
        }
    },
    imLogin: function (token, account) {
        console.log("yun xin，token:" + token + ",account:" + account);
        new IMController({
            token: token,
            account: account
        })
    },
    //根据简历ID获取简历信息
    getFromResumeInfoById(id) {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getFromResumeInfoById,
            data: {
                id: id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log("getFromResumeInfoById response", res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let body = res.data.BodyContent
                        body.comsiteContent = that.getTextFromScore(parseInt(body.CompositeScore))
                        let city = body.City
                        if (city) {
                          body.City = city.substr(0, city.length - 1);
                        }
                        that.setData({
                            resumeData: res.data.BodyContent
                        });
                    } else {
                        Toast(res.data.Message);
                    }
                } else {
                    Toast("请求失败，请检查网络连接！");
                }
            },
            fail: function(res) {
                console.log("getFromResumeInfoById fail", res);
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    //tab选项卡点击事件
    clickTabItem(e) {
        this.setData({
            currentTabPosition: e.currentTarget.id
        })
        switch (e.currentTarget.id) {
            case '2':
                //评价
                if (!this.data.commentList) {
                    this.getResumeCommentByResumeId();
                }
                break;
            case '3':
                if (!this.data.produceList) {
                    this.getMyWorks();
                }
                break;
        }
    },
    //根据简历id获取评论
    getResumeCommentByResumeId() {
        if (this.data.resumeData) {
            let id = this.data.resumeData.Id;
            let that = this;
            wx.showLoading({
                title: '加载中...',
                mask: true
            })
            wx.request({
                url: app.globalData.serverAddress.getResumeCommentByResumeId,
                data: {
                    resumeId: id,
                    currentUserInfoId: ''
                },
                header: {
                    'Authorization': "Bearer " + app.globalData.token
                },
                method: 'GET',
                success: function(res) {
                    console.log("getResumeCommentByResumeId response", res);
                    if (res.statusCode == 200) {
                        if (res.data.CodeStatus == 20000) {
                            let body = res.data.BodyContent
                            that.setData({
                                commentList: body
                            });
                        } else {
                            Toast(res.data.Message);
                        }
                    } else {
                        Toast("请求失败，请检查网络连接！");
                    }
                },
                fail: function(res) {
                    console.log("getFromResumeInfoById fail", res);
                },
                complete: function(res) {
                    wx.hideLoading();
                },
            })
        }
    },
    //根据评分获取评分文案
    getTextFromScore(score) {
        let text = '';
        switch (score) {
            case 1:
                text = '极差 ，不会再次雇佣'
                break;
            case 2:
                text = '不太满意，改善后考虑再次雇佣'
                break;
            case 3:
                text = '满足期望，值得再次雇佣'
                break;
            case 4:
                text = '超过期望，愿意推荐他人雇佣'
                break;
            case 5:
                text = '远超期望，极力推荐他人雇佣'
                break;
        }
        return text;
    },
    getMyWorks() {
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        let userInfoId = this.data.resumeData.UserInfoId
        wx.request({
            url: app.globalData.serverAddress.getMyWorks,
            data: {
                pageSize: 20,
                pageIndex: 0,
                currentUserInfoId: userInfoId,
                fileType: 0
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log(res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    console.log(res.data.BodyContent);
                    let list = res.data.BodyContent.List;
                    that.setData({
                        produceList: list
                    })
                }else{
                  Toast(res.data.Message);
                }
            },
            fail: function(res) {
                console.log("fail" + JSON.stringify(res));
                Toast(res.data.Message);
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    selectGirdItem(e) {
        let index = e.currentTarget.dataset.index;
        let fileUrl = this.data.produceList[index].FileUrl;
        wx.previewImage({
            urls: [fileUrl]
        })
    },
    checkLoginStatu(){
        if (!app.globalData.isLogin) {
            Toast("请先登录");
            setTimeout(function () {
                wx.switchTab({
                    url: '/pages/me/me'
                })
            }, 800);
            return false;
        }
        if (!app.globalData.isBindPhone){
            Toast('请先绑定手机号');
            setTimeout(function () {
                wx.navigateTo({
                    url: '/pages/mes/bind-phone/bind-phone'
                })
            }, 800);
            return false;
        }
        return true;
    },
    clickConsult() {
        if (!this.checkLoginStatu()){
            return;
        }
        this.goChat();
        // let that = this;
        // this.getEnterpriseInfoById(function(verifyStatus) {
        //     if (verifyStatus == 0) {
        //         Toast("只有企业可以联系人才哟，请先进行企业认证~");
        //     }
        //     if (verifyStatus == 1) {
        //         Toast("企业认证正在审核中...");
        //     }
        //     if (verifyStatus == 2) {
        //         that.goChat();
        //     }
        //     if (verifyStatus == 3) {
        //         Toast("企业认证失败，请前往重新认证~");
        //     }
        // });
    },
    //查看简历附件
    clickAttachment() {
        let fileType = this.data.resumeData.FileExtension
        let fileUrl = this.data.resumeData.FileUrl
        if (fileUrl) {
            wx.showLoading({
                title: '加载中...',
                mask: true
            })
            if (fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg') {
                wx.previewImage({
                    urls: [fileUrl]
                })
                return;
            }
            wx.downloadFile({
                url: fileUrl,
                success: function(res) {
                    wx.openDocument({
                        filePath: res.tempFilePath,
                        fileType: fileType,
                        fail(res) {
                            console.error('openDocument fail:', res)
                            Toast('打开简历附件失败')
                        }
                    })
                },
                fail: function(res) {
                    console.error('downloadFile fail：', res)
                    Toast('查看附件失败')
                },
                complete: function(res) {
                    wx.hideLoading()
                },
            })
        } else {
            Toast('他还未上传附件简历哦')
        }
    },
    goChat() {
        let account = this.data.resumeData.UserInfoId;
        if (!account) {
            return;
        }
        store.dispatch({
            type: 'CurrentChatTo_Change',
            payload: `p2p-${account}`
        })
        wx.navigateTo({
            url: `/partials/chating/chating?chatTo=${account}&type=p2p&title=${this.data.resumeData.Name}&positionId=${this.data.resumeData.JobPosition}`,
        });
    },
    toAgreement() {
        app.globalData.globalWebUrl = app.globalData.agreementUrl.employUrl;
        wx.navigateTo({
            url: '/pages/agreement-web/agreement-web?title=雇佣规则'
        })
    },
    clickSign() {
        if (!app.globalData.isLogin) {
            Toast("请先登录");
            return false;
        }
        let that = this;
        this.getEnterpriseInfoById(function(verifyStatus) {
            let windowObj = that.data.windowObj;
            windowObj.isShowWindow = true;
            windowObj.isAnim = true;
            that.setData({
                windowObj: windowObj
            })
        });

    },
    // 点击查看头像
    clickProfile(){
        if (this.data.resumeData.Profile){
            wx.previewImage({
                current: this.data.resumeData.Profile,
                urls: [this.data.resumeData.Profile]
            })
        }
    },
    clickFullWindow() {
        let windowObj = this.data.windowObj;
        windowObj.isShowWindow = false;
        windowObj.isAnim = false;
        this.setData({
            windowObj: windowObj,
            authChecked: false
        })
    },
    //点击金额后面的问号图标
    clickAmountHint(){
        wx.navigateTo({
            url: '/pages/new-pages/refund-rule/refund-rule'
        })
    },
    //结算方式
    clickPayWay(event) {
        let index = event.target.id;
        this.setData({
            windowPosition: index
        });
    },
    checkboxChange() {
        let currentCheck = this.data.authChecked;
        this.setData({
            authChecked: !currentCheck
        });
    },
    startDatePickerChange(e) {
        let indexs = this.data.pickerDateIndexs;
        let pickerDate = this.data.pickerDate;
        let startDate = pickerDate[0][indexs[0]] + "-" + pickerDate[1][indexs[1]] + "-" + pickerDate[2][indexs[2]];
        let key = this.data.windowPosition == 1 ? 'startDate' : 'endDate';
        this.setData({
            [key]: startDate
        })
    },
    startDateItemPickerChange(e) {
        let data = {
            pickerDateIndexs: this.data.pickerDateIndexs
        }
        switch (e.detail.column) {
            case 0:
                data.pickerDateIndexs[0] = e.detail.value;
                break;
            case 1:
                data.pickerDateIndexs[1] = e.detail.value;
                let day = datePickerUtils.getMonthDay(this.data.pickerDate[0][data.pickerDateIndexs[0]], this.data.pickerDate[1][e.detail.value]);
                this.setData({
                    [`pickerDate[2]`]: day
                });
                break;
            case 2:
                data.pickerDateIndexs[2] = e.detail.value;
                break;
        }

        this.setData(data);
    },
    workTimeInput(e) {
        let value = parseInt(e.detail.value)
        if(value > 160){
            Toast('月工作小时最大160h');
            return;
        }
        // 订单金额 = 工作时长 * 时薪
        let orderAmount = value * parseInt(this.data.resumeData.HourlySalary)
        if (!orderAmount) {
            orderAmount = 0;
        }
        let managerAmount = parseFloat((orderAmount * 0.1).toFixed(2));//管理费为订单金额的10%
        let totalAmount = orderAmount + managerAmount;
        if (this.data.isOpenVip) {
          totalAmount = orderAmount;
        }
        this.setData({
            workTime: value,
            orderAmount: orderAmount,
            managerAmount: managerAmount,
            totalAmount: totalAmount ? totalAmount : 0
        })
    },
    orderAmountInput(e) {
        let orderAmount = parseFloat(e.detail.value);
        let managerAmount = parseFloat((orderAmount * 0.1).toFixed(2));
        if (!orderAmount) {
            managerAmount = 0;
        }
        let totalAmount = orderAmount + managerAmount;
        if (this.data.isOpenVip) {
            totalAmount = orderAmount;
        }
        this.setData({
            orderAmount: orderAmount,
            managerAmount: managerAmount,
            totalAmount: totalAmount ? totalAmount : 0
        });
    },
    clickOpenVip() {
        let managerAmount = this.data.orderAmount;
        if (!this.checkAmount(managerAmount)) {
            return;
        }
        let isOpenVip = !this.data.isOpenVip;
        let total = 0;
        if (isOpenVip) {
            total = this.data.totalAmount - managerAmount + 499;
        } else {
            total = managerAmount + this.data.orderAmount;
        }
        this.setData({
            isOpenVip: isOpenVip,
            totalAmount: total
        })
    },
    clickPay() {
        let startTime = this.data.startDate;
        let position = this.data.windowPosition;
        // if (position == 1 && !startTime) {
        //     Toast("请选择开始时间");
        //     return;
        // }
        let workTime = this.data.workTime;
        if (position == 1 && !workTime) {
            Toast("请输入月工作时长");
            return;
        }
        // let endTime = this.data.endDate;
        // if (position == 2 && !endTime) {
        //     Toast("请选择截止时间");
        //     return;
        // }
        let orderAmount = this.data.orderAmount;
        if (!this.checkAmount(orderAmount)) {
            return;
        }
        let isCheckAuth = this.data.authChecked;
        if (!isCheckAuth) {
            Toast("请先阅读《闲将服务协议》");
            return;
        }
        let data = {
            "OrderType": 0,
            "OrderAmount": 0,
            "SelectVIP": 0
        };
        data.UserInfoId = app.userInfo.Id;
        data.ResumeInfoId = this.data.resumeData.Id;
        data.ContactNumber = this.data.phoneNumber;
        data.OrderType = position;
        data.OrderAmount = orderAmount;
        data.WorkTime = workTime;
        data.Time = formatTime(new Date())
        let vipStatus = this.data.vipStatus;
        if (vipStatus == 1) {
            //已开通
            data.SelectVIP = 2;
        } else {
            data.SelectVIP = this.data.isOpenVip ? 1 : 0;
        }
        console.log("发起支付的参数", data);
        this.buyResume(data);
    },
    checkAmount(amount) {
        if (!amount) {
            Toast("请输入工作时长");
            return false;
        }
        let regAmount = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        if (!regAmount.test(amount)) {
            Toast("请输入正确的金额");
            return false;
        }
        if (Number.parseFloat(amount) <= 0) {
            Toast("订单金额不能为0元，请修改后再提交哟~");
            return false;
        }
        return true;
    },
    buyResume(data) {
        wx.showLoading({
            title: '发起支付中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.buyResume,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function(res) {
                console.log("buyResume response", res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        wx.requestPayment({
                            timeStamp: res.data.BodyContent.timeStamp,
                            nonceStr: res.data.BodyContent.nonceStr,
                            package: res.data.BodyContent.package,
                            signType: res.data.BodyContent.signType,
                            paySign: res.data.BodyContent.paySign,
                            success: function(res) {
                                wx.navigateBack({
                                    delta: 1,
                                });
                                wx.navigateTo({
                                    url: '/pages/new-pages/my-employee/my-employee',
                                });
                            },
                            fail: function(res) {
                                console.log("fail" + JSON.stringify(res));
                            },
                            complete: function(res) {},
                        })
                    } else {
                        Toast(res.data.Message);
                    }
                } else {
                    Toast("发起支付失败，请检查网络连接");
                }
            },
            fail: function(res) {
                console.log("buyResume fail", res);
                Toast("发起支付失败，请检查网络连接");
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    //弹出窗口滑动拦截
    interceptCatchMove() {},

    //弹出窗口事件拦截
    catchWindow() {},
    getEnterpriseInfoById(func) {
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getEnterpriseInfoById,
            data: {
                userInfoId: app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log('getEnterpriseInfoById success', res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let verifyStatus = res.data.BodyContent.VerifyStatus;
                        let vipStatus = res.data.BodyContent.VIPStatus;
                        that.setData({
                            vipStatus: vipStatus,
                            isOpenVip: vipStatus == 1
                        })
                        if (verifyStatus == 2) {
                            app.globalData.enterpriseInfo = res.data.BodyContent;
                        }
                        if (func) {
                            func(verifyStatus);
                        }
                    } else {
                        func(0);
                    }
                } else {
                    Toast("网络出问题啦，请重试！");
                }
            },
            fail: function(res) {
                console.log("getEnterpriseInfoById fail", res)
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})